﻿
using System;
using System.Collections.Generic;
using System.Text;

using System.Linq;
using OddUserManager.Data.IRepositories;
using OddUserManager.Model;

namespace OddUserManager.Service.IServices
{
    public class MenusService : IMenusService
    {
        private readonly IMenuRepository _menuRepository;
        private readonly IAppUserRepository _userRepository;
        private readonly IRoleRepository _roleRepository;
        public MenusService(IMenuRepository menuRepository, IAppUserRepository userRepository, IRoleRepository roleRepository)
        {
            _menuRepository = menuRepository;
            _userRepository = userRepository;
            _roleRepository = roleRepository;
        }

        public void DeleteBatchMenus(List<int> ids)
        {
            _menuRepository.DeleteBatch(ids);
        }

        public void DeleteMenusById(int id)
        {
            _menuRepository.Delete(id);
        }

        public List<Menus> GetAllList()
        {
            return _menuRepository.GetAllList().ToList();
        }

        public Menus GetMenusById(int id)
        {
            return _menuRepository.Get(id);
        }

        public List<Menus> GetMenusByParent(int parentId, int startPage, int pageSize, out int rowCount)
        {
            var allMenus = _menuRepository.GetAllList().ToList();
            var pm = allMenus.FirstOrDefault(p => p.Id == parentId);
            rowCount = allMenus.Count(p => p.ParentId == parentId);
            var menus = allMenus.Where(p => p.ParentId == parentId).Skip((startPage - 1) * pageSize).Take(pageSize).OrderBy(p => p.SerialNumber).ToList();
            menus.ForEach(p => p.ParentName = pm.Name);
            return menus;
        }

        public List<Menus> GetMenusByUserId(int userId)
        {
            List<Menus> result = new List<Menus>();
            var allMenus = _menuRepository.GetAllList().OrderBy(it => it.SerialNumber);
            
            var user = _userRepository.GetWithRoles(userId);
            if (user == null)
                return result;

            if (user.Id == 1)//超级管理员
            {
                return allMenus.ToList();
            }

            var userRoles = user.UserRoles;
            List<int> menuIds = new List<int>();
            foreach (var role in userRoles)
            {
                menuIds = menuIds.Union(_roleRepository.GetAllMenuListByRole(role.RoleId)).ToList();
            }
            result = allMenus.Where(it => menuIds.Contains(it.Id)).OrderBy(it => it.SerialNumber).ToList();
            return result;
        }

        public bool InsertOrUpdateMenus(Menus menu)
        {
            var result = _menuRepository.InsertOrUpdate(menu);
            return result;
        }
    }
}
